package org.example.buysystem.controller;


import cn.hutool.core.date.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.example.buysystem.common.Result;
import org.example.buysystem.entity.Cart;
import org.example.buysystem.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/cart")
@CrossOrigin
@Api(value = "购物车模块",tags = {"购物车模块"})
public class CartController {

    @Autowired
    private CartService cartService;

    @PostMapping
    @ApiOperation( "添加商品到购物车")
    public Result addGoodToCart(@RequestBody Cart cart){
        cart.setCreateTime(DateUtil.now());
        cartService.saveOrUpdate(cart);
        return Result.success();

    }

    @GetMapping("/userid/{userId}")
    @ApiOperation("根据用户id获取购物车")
    public Result getCartByUserId(@PathVariable Long userId){
        return Result.success(cartService.getCartByUserId(userId));
    }

    @DeleteMapping("/{id}")
    @ApiOperation("根据id删除购物车中的商品")
    public Result deleteGoodFromCart(@PathVariable Long id){
        cartService.removeById(id);
        return Result.success();
    }


    @PutMapping
    @ApiOperation(value = "修改购物车")
    public Result update(@RequestBody Cart cart) {
        cartService.updateById(cart);
        return Result.success();
    }

    //查找所有用户的购物车
    @GetMapping
    @ApiOperation(value = "查询所有用户的购物车")
    public Result findAll() {
        List<Cart> list = cartService.list();
        return Result.success(list);
    }

    /*
查询
*/
    //根据购物车id查询
    @GetMapping("/{id}")
    @ApiOperation(value = "根据购物车id查询")
    public Result selectById(@PathVariable Long id) {
        return Result.success(cartService.getById(id));
    }

    @GetMapping("/{ids}")
    @ApiOperation(value = "根据购物车id批量查询")
    public Result selectByIds(@PathVariable String ids) {
        List<Cart> list=new ArrayList<>();
        for (String id : ids.split(",")){
            list.add(cartService.getById(id));
        }

        return Result.success(list);
    }
}
